package com.google.code.esper.spring;

import com.espertech.esper.client.EPAdministrator;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esper.client.EPStatement;
import com.espertech.esper.client.EPSubscriberException;
import com.espertech.esper.client.StatementAwareUpdateListener;
import com.espertech.esper.client.UpdateListener;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.AbstractFactoryBean;

/**
 *
 */
public class EPStatementFactoryBean extends AbstractFactoryBean<EPStatement> implements FactoryBean<EPStatement>, BeanNameAware {

    private String epl;
    private String name;
    private Object userObject;
    private List<? extends Object> listeners  = Collections.emptyList();
    private EPAdministrator administrator;

    @Override
    public Class<? extends EPStatement> getObjectType() {
        return EPStatement.class;
    }

    @Override
    protected EPStatement createInstance() throws Exception {
        EPStatement statement = administrator.createEPL(epl, name, userObject );
        for (Object listener : listeners) {
            if (listener instanceof UpdateListener) {
                statement.addListener((UpdateListener) listener);
            } else if (listener instanceof StatementAwareUpdateListener) {
                statement.addListener((StatementAwareUpdateListener) listener);
            } else {
                try {
                    statement.setSubscriber(listener);
                } catch (EPSubscriberException ex) {
                    throw new BeanInitializationException("Listener class '" + listener.getClass().getName() + "' is neither an UpdateListener nor a valid subscriber", ex);
                }
            }
        }
        // TODO listeners
        return statement;

    }

    public void setBeanName(String name) {
        this.name = name;
    }

    public void setUserObject(Object userObject) {
        this.userObject = userObject;
    }

    public void setEpl(String epl) {
        this.epl = epl;
    }

    public void setListeners(List<? extends Object> listeners) {
        this.listeners = listeners;
    }

    public void setServiceProvider(EPServiceProvider serviceProvider) {
        this.administrator = serviceProvider.getEPAdministrator();
    }
}
